package 多线程.单例模式;

public class Singleton {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Singleton4.getInstance());
            }
        };
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
        t1.start();
        t2.start();
    }
}


//懒汉式线程不安全
class Singleton1 {
    private static Singleton1 instance = null;

    private Singleton1() {
    }

    public static Singleton1 getInstance() {
        if (instance == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new Singleton1();
        }
        return instance;
    }
}

//懒汉式线程安全
class Singleton2 {
    private static Singleton2 instance = null;

    private Singleton2() {
    }

    public static synchronized Singleton2 getInstance() {
        if (instance == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new Singleton2();
        }
        return instance;
    }
}

//懒汉式线程安全
//双检锁/双重校验锁
class Singleton3 {
    private static Singleton3 instance = null;

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        if (instance == null) {
            synchronized (Singleton3.class) {
                if (instance == null) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    instance = new Singleton3();
                }
            }
        }
        return instance;
    }
}

//饿汉式线程安全

class Singleton4 {
    private static Singleton4 instance = new Singleton4();

    private Singleton4() {
    }

    public static Singleton4 getInstance() {

        return instance;
    }
}
//饿汉式 懒加载
class Singleton5 {
    private static class Singleton5Holder{
        private static Singleton5 instance = new Singleton5();
    }

    private Singleton5() {
    }

    public static Singleton5 getInstance() {

        return Singleton5Holder.instance;
    }
}
